package com.ddw.weewar.api;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * Represents a utilities class for helping with xml
 */
public abstract class XmlUtils {

    /**
     * Attempts to parse an xml string into an xml document
     * @param xml the xml to parse
     * @return an xml document instance
     * @throws RuntimeException if there is a problem parsing the xml
     */
    public static Document parse(String xml) throws RuntimeException {
        // Create xml parser
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException("Failed to create document builder", e);
        }

        // Parse the response into xml
        try {
            StringReader reader = new StringReader(xml);
            return builder.parse(new InputSource(reader));
        } catch (SAXException e) {
            throw new RuntimeException("Sax failure when parsing as xml", e);
        } catch (IOException e) {
            throw new RuntimeException("IO failure when parsing as xml", e);
        }
    }

}
